// pages/login/login.js

const http = require('../../utils/http')
const config = require('../../utils/config')
const api = require('../../utils/extendApi')
const crypto = require('../../utils/crypto')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    toRegister: false,
    userName: '',
    passWord: '',
    videoSrc: '../..',
    posterImage: 'https://example.com/poster.jpg'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      //toRegister=0(false)是区登录，=1(true)是去注册
      toRegister: options.isRegister == 1
    })
    console.log("toRegister", this.data.toRegister)
  },

  getInputVal(e) {
    console.log(e);
    if (e.currentTarget.dataset.type == 'account') {
      this.setData({
        userName: e.detail.value,
      })
    } else if (e.currentTarget.dataset.type == 'password') {
      this.setData({
        passWord: e.detail.value,
      })
    }
  },


  /***
   * 
   * 用户登录或者注册
   * 
   */
  handleLoginOrRegister(e) {
    if (!this.data.userName.trim()) {
      api.toast({
        title: '请输入用户名',
        icon: 'none'
      })
      return
    }
    if (this.data.password === '') {
      api.toast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }
    var toRegister = this.data.toRegister;
    console.log("toRegister", toRegister)
    var page = this
    var params = {
      url: this.data.toRegister ? config.registerUrl : config.loginUrl,
      method: this.data.toRegister ? "POST" : "GET",
      data: {
        name: this.data.userName,
        password: crypto.encrypt(this.data.passWord)
      },
      callBack(res) {
        console.log("res", res);
        if (toRegister) {
          if (res == null) {
            wx.showToast({
              title: '已存在账号！请尝试其他用户名进行注册',
              icon: "none",
            })
          } else {
            // 注册成功
            page.setData({
              name: res.name,
              password: res.password,
            })
            wx.setStorageSync('userId', res.id)
            wx.setStorageSync('isLogin', true)
            // 跳转首页
            wx.switchTab({
              url: '../index/index',
            })
          }
        } else {
          if (res == null) {
            wx.showToast({
              title: '账号或者密码错误',
              icon: 'none',
            })
          } else {
            //登录成功    
            wx.setStorageSync('userId', res.id)
            wx.setStorageSync('isLogin', true)
            // 跳转首页
            wx.switchTab({
              url: '../index/index',
            })
          }
        }

      },
      errCallBack(res) {}
    }
    console.log(params);
    http.request(params)
  },


  changeLoginOrRegister() {
    let str = this.data.toRegister ? '0' : '1'
    wx.redirectTo({
      url: '/pages/login/login?isRegister=' + str,
    })
  },

})